package com.qa.service.impl;

import com.qa.constant.UserConstant;
import com.qa.entity.LoginUser;
import com.qa.entity.User;
import com.qa.mapper.AuthorityMapper;
import com.qa.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 徐
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthorityMapper authorityMapper;

    /**
     * @param username String
     * @return UserDetails
     * @throws UsernameNotFoundException UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询数据库，用户名就是邮箱
        User user = userMapper.getUserByMail(username);

        if (user == null) {
            throw new UsernameNotFoundException(UserConstant.USER_NOT_FOUND);
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> list = authorityMapper.getAuthorityByUserId(user.getId());
        return new LoginUser(user, list);
    }
}
